package com.zcz.item.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zcz.common.pojo.PageResult;
import com.zcz.item.mapper.BrandMapper;
import com.zcz.item.pojo.Brand;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @author 王卫帅
 */
@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;

    public PageResult<Brand> queryBrandsByPage(String key, Integer page, Integer rows, String sortBy, boolean desc) {
        //模糊查询
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        //根据mane 模糊查询 ，或者根据首字母查询
        if (StringUtils.isNotBlank(key)){
            criteria.andLike("name","%"+key+"%").orEqualTo("letter",key);
        }
        //添加分页条件
        PageHelper.startPage(page,rows);
        //添加排序条件
        if (StringUtils.isNotBlank(sortBy)){
            example.setOrderByClause(sortBy +" "+(desc ? "desc" : "asc"));
        }
        System.err.println(example);
        List<Brand> brands = this.brandMapper.selectByExample(example);
        System.err.println(brands);
        //包装成pageInfo
        PageInfo <Brand> pageInfo = new PageInfo<>(brands);
        //包装成分页结果集返回   总条数             记录信息
        return new PageResult<>(pageInfo.getTotal(),pageInfo.getList());
    }
    @Transactional
    public void saveBrand(Brand brand, List<Long> cids) {
        this.brandMapper.insertSelective(brand);

            cids.forEach(cid->{
                this.brandMapper.insertCategoryAndBrand(cid,brand.getId());
            });

    }
}
